package chris.rpc;

import chris.ConFactory;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RPCServer
 *
 * @author nanxin.chen
 * @since 2017/7/14
 */
public class RPCServer {

    public static final String RPC_QUEUE_NAME = "rpc_queue";

    public static int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fib(n - 1) + fib(n - 2);
    }


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory cf = ConFactory.getConnectionFactory();
        Connection con = cf.newConnection();
        final Channel channel = con.createChannel();

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        System.out.println(" [x] Awaiting RPC requests");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties
                        .Builder()
                        .correlationId(properties.getCorrelationId())
                        .build();

                String message = new String(body, "UTF-8");
                int n = Integer.parseInt(message);

                String response = "";
                System.out.println(" [.] fib(" + message + ")");
                response += fib(n);

                channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("utf-8"));
                channel.basicAck(envelope.getDeliveryTag(), false);

            }
        };

        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
    }
}
